// 筛选栏组件
// 用于展示和选择筛选条件，支持分组显示和展开/收起功能
import React, { useState } from 'react';
import './FilterBar.css';

const MAX_VISIBLE = 10; // 一行最多显示多少个选项

// 筛选栏组件属性接口
interface FilterBarProps {
  options: Record<string, string[]>; // 筛选选项，key为分组名，value为选项数组
  selected: Record<string, string>; // 当前选中的选项，key为分组名，value为选中的选项
  onSelect: (group: string, item: string) => void; // 选择回调函数
}

const FilterBar: React.FC<FilterBarProps> = ({ options, selected, onSelect }) => {
  // 记录每个分组的展开状态
  const [expanded, setExpanded] = useState<Record<string, boolean>>({});

  // 切换分组展开/收起状态
  const handleToggle = (group: string) => {
    setExpanded((prev) => ({ ...prev, [group]: !prev[group] }));
  };

  return (
    <div className="filter-bar">
      {/* 遍历所有筛选分组 */}
      {Object.entries(options).map(([group, items]) => {
        // 先对每组去重再分割，避免重复选项
        const dedupedItems = Array.from(new Set(items));
        const isExpand = expanded[group]; // 当前分组是否展开
        // 根据展开状态决定显示哪些选项
        const visibleItems = isExpand ? dedupedItems : dedupedItems.slice(0, MAX_VISIBLE);
        const hasMore = dedupedItems.length > MAX_VISIBLE; // 是否有更多选项需要展开

        return (
          <div className="filter-group" key={group}>
            {/* 分组标题 */}
            <span className="group-title">{group}：</span>
            
            {/* 显示可见的选项 */}
            {visibleItems.map(item => (
              <span
                key={item}
                className={selected[group] === item ? 'filter-item active' : 'filter-item'}
                onClick={() => onSelect(group, item)}
              >
                {item}
              </span>
            ))}
            
            {/* 更多按钮：当有更多选项且未展开时显示 */}
            {hasMore && !isExpand && (
              <span className="filter-item more-btn" onClick={() => handleToggle(group)}>
                更多 <span style={{fontSize:12}}>▼</span>
              </span>
            )}
            
            {/* 展开后的额外选项 */}
            {hasMore && isExpand && (
              <>
                <div className="filter-group-more">
                  {/* 显示展开后的额外选项 */}
                  {dedupedItems.slice(MAX_VISIBLE).map(item => (
                    <span
                      key={item}
                      className={selected[group] === item ? 'filter-item active' : 'filter-item'}
                      onClick={() => onSelect(group, item)}
                    >
                      {item}
                    </span>
                  ))}
                </div>
                {/* 收起按钮 */}
                <span className="filter-item more-btn" onClick={() => handleToggle(group)}>
                  收起 <span style={{fontSize:12}}>▲</span>
                </span>
              </>
            )}
          </div>
        );
      })}
    </div>
  );
};

export default FilterBar; 